package cn.codenest.util.impl;

import cn.codenest.util.RbmqService;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;

/**
 * @author ：Hyman
 * @date ：Created in 2021/7/6 12:10
 * @description：
 * @modified By：
 * @version: $
 */
public class RbmqServiceImpl implements RbmqService {

    private String rabbitMqHost = "127.0.0.1";
    private String rabbitMqUsername = "guest";
    private String rabbitMqPassword = "guest";
    private Integer rabbitMqPort = 5672;
    private Integer rabbitMqTimeOut = 10000;


    @Override
    public void sendTopicMsg(String order) throws IOException, TimeoutException {
        Connection connection = null;
        Channel channel = null;
        try {
            ConnectionFactory factory = new ConnectionFactory();
            factory.setHost(this.rabbitMqHost);
            factory.setPort(this.rabbitMqPort);
            factory.setConnectionTimeout(this.rabbitMqTimeOut);
            factory.setUsername(this.rabbitMqUsername);
            factory.setPassword(this.rabbitMqPassword);
            factory.setVirtualHost("/");
            connection = factory.newConnection();
            channel = connection.createChannel();

            channel.exchangeDeclare("dlx.exchange", "topic", true, false, null);
            channel.queueDeclare("dlx.queue", true, false, false, null);
            channel.queueBind("dlx.queue", "dlx.exchange", "#");

            channel.exchangeDeclare("order.exchange", "topic", true, false, null);

            Map<String, Object> agruments = new HashMap<String, Object>();
            agruments.put("x-dead-letter-exchange", "dlx.exchange");
            channel.queueDeclare("order.queue", true, false, false, agruments);
            channel.queueBind("order.queue", "order.exchange", "order.#");

            AMQP.BasicProperties properties = new AMQP.BasicProperties.Builder()
                    .deliveryMode(2)
                    .contentEncoding("UTF-8")
                    .expiration("30000")
                    .build();
            channel.basicPublish("order.exchange", "order.new", properties, order.getBytes("UTF-8"));
        } finally {
            if (channel != null && channel.isOpen()) {
                channel.close();
            }
            if (connection != null && connection.isOpen()) {
                connection.close();
            }
        }
    }


}
